package com.vpen.blog.controller;

import com.vpen.blog.common.ReturnResult;
import com.vpen.blog.entity.User;
import com.vpen.blog.entity.UserLogin;
import com.vpen.blog.service.UserService;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * -@Version 1.0
 * -@Author:Vpen
 * -@Date:2021/7/7 22:56
 * -@Content:
 */
@RestController
@RequestMapping("/api")
public class LoginController {
    @Autowired
    UserService userService;
        // 登录接口
        @PostMapping("/login/check")
        public ReturnResult checkLogin(@RequestBody HashMap<String, Object> map, HttpServletRequest request){
            UserLogin userLoginPost = encodeUserLogin(map);// 包含前端表单发送来的所有信息

            String code = userLoginPost.getCode(); // 获取验证码
            System.out.println(map);

            if (!validCode(code,request)){ // 验证验证码
                return ReturnResult.getInstance().fail("验证码错误");
            }
            return userService.login(userLoginPost, request);//验证登录
        }

        // 获取登录用户的信息
        @GetMapping("/admin/info")
        public ReturnResult UserInfo(Principal principal){
            if (principal == null) {
                return null;
            }
            String name = principal.getName();
            User user=userService.getUserByUserName(name);
            user.setPassword(null);
            return ReturnResult.getInstance().success(user);
        }

        // 退出登录，由前端删除请求头里的token
        @GetMapping("/logout")
        public ReturnResult Logout(){
            return ReturnResult.getInstance().success("注销成功",null);
        }

        /**
         * 作者:Vpen
         * 描述:校验前端提交的验证码
         * */
        private boolean validCode(String code,HttpServletRequest request){
            boolean yz = false; // 验证
            String verCode = (String) request.getSession().getAttribute("captcha");// 获取session中的验证码
            System.out.println(verCode);
            if (code!=null&&verCode!=null && code.toLowerCase().equals(verCode.trim().toLowerCase())) {// 判断验证码
                yz=true;
            }
            return yz;
        }

        /**
         * 作者:Vpen
         * 描述: 封装登录实体类请求
         * */
        private UserLogin encodeUserLogin(Map<String,Object> map){
            String code = (String) map.get("code");
            String username =(String) map.get("username");
            String password =(String) map.get("password");
            Boolean rememberMe = (Boolean) map.get("RememberMe");
            return new UserLogin(username,password,code,rememberMe);
        }

}
